﻿using System.Collections;

/// <summary>
/// 加入房间
/// </summary>
public class Game_JoinRoom2State : GameState
{
	static Game_JoinRoom2State _inst;

	public static Game_JoinRoom2State inst {
		get {
			if (_inst == null) {
				_inst = new Game_JoinRoom2State ();
			}
			return _inst;
		}
	}


	public override void Enter ()
	{
		DebugInfo.Log ("Enter Game_JoinRoom2State");

		RequestJoinRoom ();
	}

	public override void Leave ()
	{
		DebugInfo.Log ("Leave Game_JoinRoom2State");
	}

	public override bool ProcessPacket (IOMessage message)
	{
		switch (message.code) {
		case IOCmds.SMSG_JOIN_ROOM:
		case IOCmds.SMSG_SET_PLAYER_RECONNECT:
			HandleJoinRoomFromGame (message);
			return true;

		case IOCmds.WS_CONN_OPEN:
			// 与服务器的连接打开
			UIRootController.inst.ShowMask (false);
			RequestJoinRoom ();
			return true;

		case IOCmds.WS_CONN_CLOSED:
			// 连接失败或者/连接断开
			UIRootController.inst.ShowMask (true);
			TimerController.inst.CallAfter (0.3f, args => {
				NetIOController.inst.Connect (null);
			});
			return true;
		}

		return base.ProcessPacket (message);
	}

	/// <summary>
	/// 处理游戏服务器发来的加入房间消息
	/// </summary>
	/// <param name="message"></param>
	void HandleJoinRoomFromGame (IOMessage message)
	{
		if (message.state == IOStates.STATE_OK) {
			UIRootController.inst.ShowMask (false);

			DebugInfo.Log ("玩家加入房间成功");

			// 初始化游戏界面UI
			GameProcedure.inst.InitUI ();

			// 处理数据
			GameDataKernel.inst.HandleMessage (message);

			// 进入等待开始状态
			//if (!GameDataKernel.inst.playing) {
				GameProcedure.inst.SwitchState (Game_WaitingState.inst);
			//}
		}
	}
}
